package com.ailanyin.admin.controller;


import com.ailanyin.admin.service.ExceptionLogService;
import com.ailanyin.common.exception.ApiException;
import com.ailanyin.common.result.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 *
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/15 0015 下午 16:43
 */
@ControllerAdvice
public class BaseExceptionController {

    @Autowired
    private ExceptionLogService exceptionLogService;

    /**
     * 非自定义异常
     * 存进数据库
     *
     * @param e Exception
     * @return AjaxResult
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public AjaxResult error(Exception e){
        e.printStackTrace();
        try {
            exceptionLogService.insertExceptionLog(e);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 自定义异常, 控制台不打印
     *
     * @param e ApiException
     * @return AjaxResult
     */
    @ExceptionHandler(ApiException.class)
    @ResponseBody
    public AjaxResult handlerBingException(ApiException e) {
        return AjaxResult.error(e.getMessage());
    }
}
